<?php

namespace app\admin\controller;

use think\Lang;
use League\Csv\Reader;
use League\Csv\Statement;

/**
 * ============================================================================
 * 佳皿一站式,酒水服务类综合平台
 * ============================================================================
 * 版权所有 2019-2028 成都佳皿商贸有限公司，并保留所有权利。
 * 网站地址: http://www.91buys.com
 * ============================================================================
 * 控制器
 */
class Tasting extends AdminControl {

    private $_ext = ['csv'];
    const EXPORT_SIZE = 1000;
    const SYNC_QIANHAI_ERROR    = 3;
    const SYNC_QIANHAI_SUCCESS  = 2;

    const SEND_HAIGUAN_ERROR    = 3;
    const SEND_HAIGUAN_SUCCESS  = 2;

    public function _initialize() {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/tasting.lang.php');
    }

    /**
     * 活动列表/删除活动
     */
    public function index() {
        $tasting_model = model('tasting');
        //条件
        $condition = array();
        //状态
        if ((input('param.searchstate'))) {
            $state = intval(input('param.searchstate')) - 1;
            $condition['tasting_state'] = "$state";
        }
        //标题
        if ((input('param.searchtitle'))) {
            $condition['tasting_title'] = array('like', "%" . input('param.searchtitle') . "%");
        }
        //有效期范围
        if ((input('param.searchstartdate')) && (input('param.searchenddate'))) {
            $startdate = strtotime(input('param.searchstartdate'));
            $enddate = strtotime(input('param.searchenddate'));
            $condition['tasting_enddate'] = array('egt',$startdate);
            $condition['tasting_startdate'] = array('elt',$enddate);
        }
        //活动列表
        $tasting_list = $tasting_model->gettastingList($condition,10,'tasting_id desc');
        //输出
        $this->assign('show_page', $tasting_model->page_info->render());
        $this->assign('tasting_list', $tasting_list);
        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /**
     * 新建活动/保存新建活动
     */
    public function add() {
        $tasting_model = model('tasting');
        //查询上一个活动的添加时间
        $last_tasting_enddate = $tasting_model->order('tasting_id desc')->value('tasting_enddate');
        if (request()->isPost()) {
            //提交表单
            $data = [
                'tasting_title' => input('post.tasting_title'),
                'tasting_startdate' => strtotime(input('post.tasting_startdate')),
                'tasting_enddate' => strtotime(input('post.tasting_enddate')),
                'tasting_type' =>input('post.tasting_type'),
                'tasting_banner' => $_FILES['tasting_banner']['name'],
                'tasting_number' => intval(input('post.tasting_number')),
                'tasting_price' => floatval(input('post.tasting_price'))
            ];
            $tasting_validate = validate('tasting');
            if (!$tasting_validate->scene('add')->check($data)) {
                $this->error($tasting_validate->getError());
            }
           //如果开始时间小于最后一条记录的结束时间
            if($data['tasting_startdate'] < $last_tasting_enddate) $this->error(lang('tasting_start_time_error'));
            if ( $num = count($_FILES['tasting_banner']['size']) >=1 && $_FILES['tasting_banner']['size'][0] != '' ) {
                $files = $_FILES;
                $_FILES = [];
                for ($i=0;$i< $num;++$i){
                    $_FILES['tasting_banner']['name'] = $files['tasting_banner']['name'][$i];
                    $_FILES['tasting_banner']['type'] = $files['tasting_banner']['type'][$i];
                    $_FILES['tasting_banner']['tmp_name'] = $files['tasting_banner']['tmp_name'][$i];
                    $_FILES['tasting_banner']['error'] = $files['tasting_banner']['error'][$i];
                    $_FILES['tasting_banner']['size'] = $files['tasting_banner']['size'][$i];
                    //上传文件保存路径
                    $save_name = date('YmdHis') . rand(10000, 99999);
                    $file_name = 'tasting_banner';
                    $result = upload_img_to_oss(ATTACH_ACTIVITY, $file_name, $save_name);
                    if($result['code']=='10000'){
                        $tasting_banner[] = $result['result'];
                    }
                    $data['tasting_banner'] = json_encode($tasting_banner);
                }
            }else{
                $this->error(lang('tasting_new_banner_null'));
            }
            //保存
            $data['tasting_desc'] = trim(input('post.tasting_desc'));
            $data['tasting_state'] = intval(input('post.tasting_state'));

            $w['tasting_state'] = 1;
            $w['tasting_startdate'] = ['egt',$data['tasting_startdate']];
            $w['tasting_enddate'] = ['elt',$data['tasting_enddate']];
            //已经存在活动
            if(!empty($check))  $this->error(lang('tasting_exist'));
            $result = $tasting_model->addtasting($data);
            if ($result) {
                $this->log(lang('ds_add') . lang('tasting_index') . '[' . input('post.tasting_title') . ']', null);
                dsLayerOpenSuccess(lang('ds_common_op_succ'));
            } else {
                //添加失败则删除刚刚上传的图片,节省空间资源
                $this->error(lang('ds_common_op_fail'));
            }
        } else {
            $last_tasting_enddate= $last_tasting_enddate ? lang('tasting_start_time_tip').date('Y-m-d H:i:s',$last_tasting_enddate):'';
            $tasting= array(
                'tasting_type'=>'1',
                'tasting_startdate'=>TIMESTAMP,
                'tasting_enddate'=>TIMESTAMP,
                'tasting_banner'=>'',
                'tasting_desc'=>'',
                'tasting_state'=>'1',
                'last_tasting_enddate'=>$last_tasting_enddate,
            );
            $this->assign('tasting', $tasting);
            return $this->fetch('form');
        }
    }

    /**
     * 异步修改
     */
    public function ajax() {
        if (in_array(input('param.branch'), array('tasting_title'))) {
            $tasting_model = model('tasting');
            $update_array = array();
            switch (input('param.branch')) {
                /**
                 * 活动主题
                 */
                case 'tasting_title':
                    if (trim(input('param.value')) == '')
                        exit;
                    break;
                default:
                    exit;
            }
            $update_array[input('param.column')] = trim(input('param.value'));
            if ($tasting_model->edittasting($update_array, intval(input('param.id'))))
                echo 'true';
        }elseif (in_array(input('param.branch'), array('tastingdetail_sort'))) {
            $tastingdetail_model = model('tastingdetail');
            $update_array = array();
            switch (input('param.branch')) {
                /**
                 * 排序
                 */
                case 'tastingdetail_sort':
                    if (preg_match('/^\d+$/', trim(input('param.value'))) <= 0 or intval(trim(input('param.value'))) < 0 or intval(trim(input('param.value'))) > 255)
                        exit;
                    break;
                default:
                    exit;
            }
            $update_array[input('param.column')] = trim(input('param.value'));
            if ($tastingdetail_model->edittastingdetail($update_array, array('tastingdetail_id'=>intval(input('param.id')))))
                echo 'true';
        }
    }

    /**
     * 删除活动
     */
    public function del() {
        $id = intval(input('param.tasting_id'));
        if ($id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }

        $tasting_model = model('tasting');
        $tastingdetail_model = model('tastinggoods');
        //获取可以删除的数据
        $condition_arr = array();
        $condition_arr['tasting_state'] = '0'; //已关闭
        $condition_arr['tasting_enddate'] = array('lt',TIMESTAMP); //过期
        $condition_arr['tasting_id'] = $id;
        $tasting_list = $tasting_model->gettastingList($condition_arr);
        if (empty($tasting_list)) {//没有符合条件的活动信息直接返回成功信息
            ds_json_encode(10001, lang('tasting_index_help2'));
        }
        $id_arr = array();
        foreach ($tasting_list as $v) {
            $id_arr[] = $v['tasting_id'];
        }
        $condition = array();
        $condition['tasting_id'] = array('in',$id_arr);
        //只有关闭或者过期的活动，能删除
        if ($tastingdetail_model->gettasting_goodsList($condition)) {
            if (!$tastingdetail_model->deltasting_goods($condition)) {
                ds_json_encode(10001, lang('tasting_del_fail'));
            }
        }
        if ($tasting_model->deltasting($condition)) {
            $this->log(lang('ds_del') . lang('tasting_index') . '[ID:' . $id . ']', null);
            ds_json_encode(10000, lang('ds_common_del_succ'));
        }
        ds_json_encode(10001, lang('tasting_del_fail'));
    }

    /**
     * 编辑活动/保存编辑活动
     */
    public function edit() {
        $tasting_id = intval(input('param.tasting_id'));
        if ($tasting_id<=0) {
            $this->error(lang('miss_argument'));
        }
        $tasting_model = model('tasting');
        $tasting = $tasting_model->getOnetastingById($tasting_id);
        if (!request()->isPost()) {
            $tasting['tasting_banner'] = !empty( $tasting['tasting_banner']) ? json_decode( $tasting['tasting_banner'],'true'):'';
            $this->assign('tasting', $tasting);
            return $this->fetch('form');
        } else {
            //提交表单
            $data = [
                'tasting_title' => input('post.tasting_title'),
//                'tasting_startdate' => strtotime(input('post.tasting_startdate')),
//                'tasting_enddate' => strtotime(input('post.tasting_enddate')),
                'tasting_type' => input('post.tasting_type'),
                'tasting_number' => intval(input('post.tasting_number')),
                'tasting_price' => floatval(input('post.tasting_price'))
            ];
            $w['tasting_state'] = 1;
//            $w['tasting_startdate'] = ['egt',$data['tasting_startdate']];
//            $w['tasting_enddate'] = ['elt',$data['tasting_enddate']];
            $w['tasting_id'] = ['neq',$tasting_id];
            $check = $tasting_model->gettastingList($w);
            //已经存在活动
            if(!empty($check))  $this->error(lang('tasting_exist'));

            $tasting_validate = validate('tasting');
            if (!$tasting_validate->scene('edit')->check($data)) {
                $this->error($tasting_validate->getError());
            }
            //构造更新内容
            if ( $num = count($_FILES['tasting_banner']['size']) >=1 && $_FILES['tasting_banner']['size'][0] != '' ) {
                $files = $_FILES;
                $num = count($files['tasting_banner']['name']);
                $_FILES = [];
                for ($i=0;$i< $num;++$i){
                    $_FILES['tasting_banner']['name'] = $files['tasting_banner']['name'][$i];
                    $_FILES['tasting_banner']['type'] = $files['tasting_banner']['type'][$i];
                    $_FILES['tasting_banner']['tmp_name'] = $files['tasting_banner']['tmp_name'][$i];
                    $_FILES['tasting_banner']['error'] = $files['tasting_banner']['error'][$i];
                    $_FILES['tasting_banner']['size'] = $files['tasting_banner']['size'][$i];
                    //上传文件保存路径
                    $save_name = date('YmdHis') . rand(10000, 99999);
                    $file_name = 'tasting_banner';
                    $result = upload_img_to_oss(ATTACH_ACTIVITY, $file_name, $save_name);
                    if($result['code']=='10000'){
                        $tasting_banner[] = $result['result'];
                    }
                    $data['tasting_banner'] = json_encode($tasting_banner);
                }
            }
            
            $data['tasting_desc'] = trim(input('post.tasting_desc'));
            $data['tasting_state'] = intval(input('post.tasting_state'));
            
            $result = $tasting_model->edittasting($data, $tasting_id);
            if ($result !== false) {
                //删除图片
                $this->log(lang('ds_edit') . lang('tasting_index') . '[ID:' . $tasting_id . ']', null);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        }
    }

    /**
     * 活动细节列表
     */
    public function detail() {
        $tasting_id = intval(input('param.id'));
        if ($tasting_id <= 0) {
            $this->error(lang('miss_argument'));
        }
        //条件
        $condition_arr = array();
        $condition_arr['tasting_id'] = $tasting_id;
        //审核状态
        if ((input('param.searchstate'))) {
            $state = intval(input('param.searchstate')) - 1;
            $condition_arr['state'] = "$state";
        }
        //供应商名称
        if ((input('param.searchstore'))) {
            $condition_arr['store_name'] = array('like', "%" . input('param.searchstore') . "%");
        }
        //商品名称
        if ((input('param.searchgoods'))) {
            $condition_arr['goods_name'] = array('like', "%" . input('param.searchgoods') . "%");
        }

        $tastingdetail_model = model('tastinggoods');
        $tastingdetail_list = $tastingdetail_model->gettasting_goodsList($condition_arr, 10);
        //输出到模板
        $this->assign('show_page', $tastingdetail_model->page_info->render());
        $this->assign('tastingdetail_list', $tastingdetail_list);
        $this->setAdminCurItem('detail');
        return $this->fetch();
    }

    /**
     * 活动内容处理
     */
    public function deal() {
        $tastingdetail_id = input('param.tasting_goods_id');
        $tastingdetail_id_array = ds_delete_param($tastingdetail_id);
        if ($tastingdetail_id_array == FALSE) {
            ds_json_encode('10001', lang('param_error'));
        }
        $condition = array();
        $condition['tasting_goods_id'] = array('in',$tastingdetail_id_array);

        //创建活动内容对象
        $tastingdetail_state = intval(input('param.state'));
        $result =   model('tastinggoods')->edittasting_goods(['state' => $tastingdetail_state],$condition);
        if ($result>=0) {
            $this->log(lang('ds_edit') . lang('tasting_index') . '[ID:' . $tastingdetail_id . ']', null);
            if (input('param.ajax')) {
                ds_json_encode(10000,lang('ds_common_op_succ'));
            }else{
                $this->success(lang('ds_common_op_succ'));
            }
            
        } else {
            if (input('param.ajax')) {
                ds_json_encode(10001,lang('ds_common_op_fail'));
            }else{
                $this->error(lang('ds_common_op_fail'));
            }
            
        }
    }
    /**
     * 删除活动内容
     */
    public function del_detail() {
        $tastingdetail_id = input('param.tasting_goods_id');
        $tastingdetail_id_array = ds_delete_param($tastingdetail_id);
        if ($tastingdetail_id_array == FALSE) {
            ds_json_encode('10001', lang('param_error'));
        }

        $tastingdetail_model = model('tastinggoods');
        //条件
        $condition_arr = array();
        $condition_arr['tasting_goods_id'] =array('in',$tastingdetail_id_array);
        $condition_arr['state'] = array('in',array('0','2')); //未审核和已拒绝
        if ($tastingdetail_model->deltasting_goods($condition_arr)) {
            $this->log(lang('ds_del') . lang('tasting_index_content') . '[ID:' . implode(',', $tastingdetail_id_array) . ']', null);
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => lang('ds_manage'), 'url' => url('Tasting/index')
            ), array(
                'name' => 'add',
                'text' => lang('ds_new'),
                'url' => "javascript:dsLayerOpen('".url('Tasting/add')."','新增')"
            ),
        );
        if (request()->action() == 'detail') {
            $menu_array[] = array(
                'name' => 'detail', 'text' => lang('processing_application'), 'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'add_user') {
            $menu_array[] = array(
                'name' => 'add_user', 'text' => lang('tasting_export'), 'url' => 'javascript:void(0)'
            );
        }
        return $menu_array;
    }

    /**
     * @return 输入手机号添加品鉴会员
     */
    public function add_user(){
        if (request()->isPost()) {
            $tasting_id = intval(input('param.tasting_id'));
            if ($tasting_id <= 0) {
                $this->error(lang('miss_argument'));
            }
            $phone = input('param.phone');
            if (empty($phone)) {
                $this->error(lang('miss_argument'));
            }
            $phone =  str_replace('，',',',$phone);
            $phone = explode(',',$phone);
            if(empty($phone)) $this->error(lang('tasting_phone_error'));
            //查询用户的memberid
            $membersIds  = db('member')->whereIn('member_mobile',$phone)->column('member_id');
            if(empty($membersIds)) $this->error(lang('tasting_phone_error'));
            //查询选择的用户是否已经存在当前活动中
            $existsMemberids = db('tasting_member')->where('tasting_id',$tasting_id)->whereIn('member_id',$membersIds)->column('member_id');
            $newMembersIds =  array_diff($membersIds,$existsMemberids);
            foreach (array_unique($newMembersIds) as $k=>$membersId){
                $memberes[$k]['tasting_id'] = $tasting_id;
                $memberes[$k]['member_id'] = $membersId;
                $memberes[$k]['code'] = getRandomString(10);
            }
            $res = db('tasting_member')->insertAll($memberes);
            $res?  dsLayerOpenSuccess(lang('ds_common_save_succ')): $this->error(lang('ds_common_save_fail'));
        }else{
            $tasting_model = model('tasting');
            $condition['tasting_id'] = input('get.id',0);
            if($code = input('get.code')){
                $condition['tasting_member.code'] = $code;
            }
            $status = input('get.tasting_status','');
            if($status !== '' ){
                $condition['tasting_member.status'] = $status;
            }
            if ((input('param.member_status'))) {
                $state = intval(input('param.member_status'));
                if($state == 1){
                    $condition['tasting_member.member_id'] = ['neq',0];
                }
                if($state == 2){
                    $condition['tasting_member.member_id'] = ['eq',0];
                }
            }
            if($member_phone = input('get.member_name')){
                $condition['member.member_name'] = $member_phone;
            }
            $memberList = $tasting_model->getmemberList($condition,10);
            //输出
            $this->assign('show_page', $tasting_model->page_info->render());
            $this->assign('memberList', $memberList);
            $this->setAdminCurItem('add_user');
            return $this->fetch();
        }

    }

    /**excel导入品鉴用户
     * @throws \League\Csv\Exception
     */
    public function addUserExcel(){
        if(!request()->isPost()) $this->error('Request Type Error！');

        $tasting_id  = request()->param('tasting_id');
        $file = request()->file('user_excel');
        $fileNameInfo = $file->getInfo();

        if(empty($fileNameInfo))    $this->error('File Info Is NUll！');
        $fileInfoArr  = explode('.',$fileNameInfo['name']);
        $fileExt      = isset($fileInfoArr[1]) ? strtolower($fileInfoArr[1]) : '';

        if(!in_array($fileExt,$this->_ext)) $this->error('File Extension Not Allowed！');
        #使用league/csv 操作excel
        $csv = Reader::createFromPath($fileNameInfo['tmp_name']);
        $csv->setHeaderOffset(0); //set the CSV header offset
        $stmt = (new Statement())->offset(0);
        $records = $stmt->process($csv);


        foreach ($records as $t=>$record){
            if(empty($record)) continue;
            //查询用户的memberid
            $membersId  = db('member')->where('member_mobile',$record)->value('member_id');
            if(empty($membersId)) continue;
            $membersIds[] = $membersId;
        }
        //查询选择的用户是否已经存在当前活动中
        $existsMemberids = db('tasting_member')->where('tasting_id',$tasting_id)->whereIn('member_id',$membersIds)->column('member_id');
        $newMembersIds =  array_diff($membersIds,$existsMemberids);
        foreach (array_unique($newMembersIds) as $k=>$membersId){
            $memberes[$k]['tasting_id'] = $tasting_id;
            $memberes[$k]['member_id'] = $membersId;
            $memberes[$k]['code'] = getRandomString(10);
        }
        $res = db('tasting_member')->insertAll($memberes);
        $res?  dsLayerOpenSuccess(lang('ds_common_save_succ')): $this->error(lang('ds_common_save_fail'));
        $this->success('Success！');
    }
    /**
     * 导出
     *
     */
    public function export_step1() {

        $tasting_model = model('tasting');
        $condition['tasting_id'] = input('get.tasting_id',0);
        if($code = input('get.code')){
            $condition['tasting_member.code'] = $code;
        }
        $status = input('get.tasting_status','');
        if($status !== '' ){
            $condition['tasting_member.status'] = $status;
        }
        if($member_phone = input('get.member_name')){
            $condition['member.member_name'] = $member_phone;
        }
        if ((input('param.member_status'))) {
            $state = intval(input('param.member_status'));
            if($state == 1){
                $condition['tasting_member.member_id'] = ['neq',0];
            }
            if($state == 2){
                $condition['tasting_member.member_id'] = ['eq',0];
            }
        }
        if (!is_numeric(input('param.curpage'))) {
            $list = $tasting_model->getmemberList($condition);
            $count = count($list);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $this->createExcel($list);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $tasting_model->getmemberList($condition, '', '', "{$limit1},{$limit2}");
            $this->createExcel($data);
        }
    }
    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array()) {
        Lang::load(APP_PATH .'admin/lang/'.config('default_lang').'/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '手机号');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '品鉴码');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '状态');
        //data
        foreach ((array) $data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => $v['member_name']);
            $tmp[] = array('data' => $v['code']);
            $tmp[] = array('data' => $v['status']);
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('exp_od_order'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset('品鉴码', CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }

    public function tasting_code(){
        if(!request()->isPost()){

            return $this->fetch();
        }else{
            $num = input('param.number',0);
            $tasting_id = input('param.tasting_id',0);
            if(!$num || !$tasting_id) $this->error('数据有误');
            //查询已经生成了多少个
            $chekNum1 = db('tasting_member')->where('tasting_id',$tasting_id)->count();
            $chekNum2 = db('tasting')->where('tasting_id',$tasting_id)->value('tasting_number');
            if($chekNum1 >= $chekNum2) $this->error('品鉴会员数量已满');
            if($chekNum2 - $chekNum1 < $num) $this->error('最多可生成'.($chekNum2 - $chekNum1).'个品鉴码');
            for ($x=1; $x<=$num; $x++) {
               $data['code'] = getRandomString(10);
               $data['tasting_id'] = $tasting_id;
               $arr[] = $data;
            }
            $res = db('tasting_member')->insertAll($arr);
            $res?  dsLayerOpenSuccess(lang('ds_common_save_succ')): $this->error(lang('ds_common_save_fail'));
        }
    }
}
